import { downloadSheet } from "./download.js";
import { tidList } from "./tid.js";
const getSearchResultAPI = {
    keyword: "搜索信息",
    limits: "并发数",
    delay: "每次并发的间隔",
    otherOptions: {
        keyword: "搜索信息，覆盖前面的keyword",
        search_type: { "": "综合", video: "视频", media_bangumi: "番剧", media_ft: "影视", live: "直播", article: "专栏", topic: "话题", bili_user: "用户" },
        duration: { 说明: "只有在search_type为空或vedio时才有用", 0: "全部时长", 1: "10分钟以下", 2: "10-30分钟", 3: "30-60分钟", 4: "60分钟以上" },
        order: { 说明: "这个为结果的排序方式", search_type为空时可用: { totalrank: "综合排序", click: "点击数", pubdate: "发布时间", dm: "弹幕", stow: "收藏数" } },
        tids: tidList,
        说明: "这个对象是直接加在 URL 后面的请求参数",
    },
};

//limits:设置并发数为1，减小爬取的速度
async function getSearchResult(keyword, limits = 1, delay = 200, bookType = "xlsx", otherOptions = {}) {
    const baseURL = "https://api.bilibili.com/x/web-interface/search/type?"; // 注意问号
    // 构建不变的部分URL
    let message = {
        keyword,
        search_type: "video",
        order: "",
        category_id: "",
        __refresh__: true,
        _extra: "",
        duration: 1,
        highlight: 1,
        single_column: 0,
        tids: 0,
    };
    Object.assign(message, otherOptions);

    let URL =
        baseURL +
        Object.entries(message)
            .map((i) => i.join("="))
            .join("&");
    // 请求一次获取总页数
    let num = await fetch(URL + "&page=1")
        .then((res) => res.json())
        .then((res) => res.data.numPages);

    let res = await spider.Ajax({
        urls: [...Array(num).keys()].map((i) => URL + "&page=" + (i + 1)),
        returnType: "json",
        type: "start",
        limits,
        time: delay,
        options: {
            cache: "force-cache", // 强制从缓存中取出结果
        },
    });

    // 继续上面的代码
    let afterParse = res
        .map((res1) => {
            return res1.data.result;
        })
        .flat();
    console.log(afterParse);
    //打印结果

    // 通过 JSpider 的Script函数加载 sheetjs 方便我们保存为xlsx文件
    // 下面的部分为固定不变的部分，可以复用

    await downloadSheet(afterParse, "搜索" + keyword + "的信息-" + new Date().getTime(), bookType);
}
export { getSearchResult, getSearchResultAPI };
